import { Button, Form, Input, DatePicker, Table, Select, Image, Switch, Checkbox, message, Spin ,Modal} from "antd"
import "./index.css"
import { PlusOutlined, DeleteOutlined, SearchOutlined, EditOutlined, EyeOutlined } from "@ant-design/icons"
import { useState, useEffect, ReactNode, Fragment } from "react"
import * as api from "@/api/product"
import MyModal from "@/modal对话框封装/myModal"
import { getCategoryApi } from '@/api/category';
import { addProductApi,updateProductApi,delProductApi } from '@/api/product';
import { FormInstance } from "rc-field-form"
//声明表格数据的类型
type Idata = {
    description: string;
    imageUrl: string;
    inventory: number;
    price: number;
    productName: string;
    product_id: string
    updateTime: string;
    updator: string;
    category_id?: string;
    _id?: string;
}

//声明表格每一列的数据
type Icolumns = {
    align?: any;
    dataIndex: string;
    title: string;
    width?: string | number;
    key?: string,
    render?: (value: any, record: Idata, index: number) => ReactNode | any
}

const ProductList = () => {
    //声明一个要记录要被删除的商品id状态
    let [delId, setDelId] = useState<string | undefined>()
    //控制普通modal显示和隐藏
    let [isModalOpen, setIsModalOpen] = useState<boolean>()
    //记录点击当前产品的product_id
    let [currentProductId,setCurrentProductId] = useState<string | undefined>()
    // 记录当前的modal选择器中category——id
    let [currentCategoryId,setCurrentCategoryId] = useState<string | undefined>("")
    //标记点击了modal的确认按钮后是编辑还是增加 add/edit
    let [actionType,setActionType] = useState("add")
    //form中默认选择的内容
    let [selectValue, setSelectValue] = useState<{ label: string, value: string } | null>(null)
    //声明Form实例
    let [modalForm] = Form.useForm()
    //控制加载动画
    let [tableLoading, setTableLoading] = useState<boolean>(false)
    //控制modal弹框的标题
    let [modalTitle, setModalTitle] = useState('')
    //控制Modal显示和隐藏
    let [modalOpen, setModalOpen] = useState<boolean>(false)
    //声明表格数据
    let [dataSource, setDataScource] = useState<Idata[]>([])

    //声明编辑数据的方法
    let edit = async (record: Idata) => {
        //打开模态框
        setModalOpen(true)
        //更改modal的标题
        setModalTitle('修改商品')
        //设置默认选中的回显
        //请求类目数据
        let category = await getCategoryApi();
        // console.log(category)
        //通过当期编辑的数据的category,找到对应的category数据对象
        let target = category.data.data.find((item: any) => record.category_id === item.category_id);
        // console.log(target);
        // 浅拷贝record
        let newRecord = {...record}
          //把newRecord的catogory_id改成categoryName 这么做的目的是为了让select回显的是类目的名字,而不是id
        newRecord.category_id = target.categoryName
         // 设置回显数据
         modalForm.setFieldsValue(newRecord)
        //  记录当前的category_id
        setCurrentCategoryId(record.category_id)
        //当前产品的id
        setCurrentProductId(record.product_id)
    }
    // 声明删除数据的方法
    let del = async(record:Idata)=>{
      // console.log(record)
      setDelId(record.product_id)
      //弹窗
      setIsModalOpen(true)
     
    }
    //声明列数据
    let columns: Icolumns[] = [
        {
            title: "选择",
            dataIndex: 'check',
            align: 'center',
            render() {
                return <Checkbox></Checkbox>
            }
        },
        {
            align: 'center',
            title: "产品图片",
            width: 100,
            dataIndex: 'imageUrl',
            key: 'imageUrl',
            render(_) {
                return (<Image
                    width={50}
                    src={_}
                />)
            }
        },
        {
            align: 'center',
            title: "产品编号",
            dataIndex: 'product_id',
            key: 'product_id'
        },
        {
            align: 'center',
            title: '产品名称',
            dataIndex: 'productName',
            key: 'productName'
        },
        {
            align: 'center',
            title: '价格',
            dataIndex: 'price',
            key: 'price'
        },
        {
            align: 'center',
            title: '库存',
            dataIndex: 'inventory',
            key: 'inventory'
        },
        {
            align: 'center',
            title: '修改人',
            dataIndex: 'updator',
            key: 'updator'
        },
        {
            align: 'center',
            title: '修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime'
        },
        {
            align: 'center',
            title: '是否上架',
            dataIndex: 'onsell',
            key: 'onsell',
            render() {
                return <Switch></Switch>
            }
        },
        {
            align: 'center',
            title: '操作',
            dataIndex: 'action',
            render(row, record) {
                // console.log(row)
                // console.log(record)//当前列的数据
                return (
                    <Fragment>
                        <Button icon={<EyeOutlined />}>查看</Button>
                        <Button icon={<EditOutlined />} onClick={
                            () => {
                                edit(record)
                                setActionType('edit')
                            }
                        }>编辑</Button>
                        <Button danger icon={<DeleteOutlined onClick={
                          ()=>{
                            del(record)
                          }
                        }/>}>删除</Button>
                    </Fragment>
                )
            },
            key: 'action'
        }
    ]
    //选择器的加载动画
    let [selectLoading, setSelectLoading] = useState<boolean>(false)
    //类目列表
    const [categoryOption, setCategoryOption] = useState<Array<{ label: string, value: string }>>([])

    //获取产品列表，渲染表格数据
    let getProductlist = () => {
        //打开加载动画
        setTableLoading(true)
        // 发起请求
        api.getProductlistApi()
            .then(res => {
                // console.log(res)
                //因为dataSource中必须要定义key,所以使用map进行处理,增加一个key
                let data = res.data.data.map((item: Idata): Idata & { key: string } => {
                    return {
                        key: item._id as string,
                        ...item,
                        updator: item.updator ?? '暂无',
                        updateTime: item.updateTime ?? '暂无修改'
                    }
                })
                setDataScource(data)
                //关闭加载动画
                setTableLoading(false)
            })
    }
    //发起请求,获取列表数据
    useEffect(() => {
        //dom挂载之后,请求数据
        getProductlist()
    }, [])

    //选中商品类别
    const handleSelectCategory = (value: string, option: any) => {
        // console.log(value)
        // console.log(option)
        setCurrentCategoryId(value)
    }
    //点击slect,下来列表打开的时候触发
    let handleSelectDrop = () => {
        setSelectLoading(true)
        getCategoryApi()
        .then(res => {
            // console.log(res)
            let options = res.data.data.map((item: any) => ({
                label: item.categoryName,
                value: item.category_id
            }))

            setCategoryOption(options)
            setSelectLoading(false)
        })
    }
    //确定按钮,并且表单校验通过的回调
    let handleOnok = async (form: FormInstance | undefined) => {
        // 当前是增加操作
        if(actionType==='add'){
            //获取modal表单中的数据
            let formData = form?.getFieldsValue();
            // console.log(formData)
            // 添加数据
            try {
                let res = await addProductApi(formData)
                // console.log(res)
                setModalOpen(false)
                //更新数据
                getProductlist()
                //全局添加成功的提示
                res.data.state && message.success('操作成功')
            } catch (e) {
                // console.log(e)
            }
        }else if(actionType==='edit'){
            let formData = modalForm.getFieldsValue();
            // console.log(currentCategoryId);    
            // console.log(formData);  
            // 浅拷贝formData，由于formData中，直接
            let data = {...formData}   
            data.category_id = currentCategoryId
            data.product_id = currentProductId
            // console.log(data);
            try{
                let res = await updateProductApi(data)
                // console.log(res)
                setModalOpen(false)
                if(res.data.state){
                    message.success('修改成功')
                    //更新数据
                    getProductlist()
                }
            }catch(e){
                console.log(e);    
            }
            
        }
    }
    //取消按钮的回调
    let handleOncancel = (form: FormInstance | undefined) => {
        console.log(form)
        setModalOpen(false)
        //清除Form实例上的data数据
        form?.resetFields()
        message.warning('已取消操作')
    }
    // console.log(selectValue)
    //确定按钮
    let handleOk = async () => {
        try {
            let res = await delProductApi(delId as string);
            console.log(res)
            if(res.data.state){
                message.success('删除成功')
            }
            //更新列表
            getProductlist();
            //关闭弹框
            setIsModalOpen(false)
        } catch (e) {
            console.log(e)
        }
    }
    let handleCancel = () => {
        setIsModalOpen(false)
        message.warning('已取消删除')
    }
    return (
        <div className="list_container">
            {/* 确认对话框 */}
            <Modal title="删除提示" okText='确认删除' centered cancelText='取消删除' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>是否要删除这条数据?</p>
            </Modal>
            {/* 对话框 */}
            <MyModal formInstance={modalForm} title={modalTitle} open={modalOpen} onOk={handleOnok} onCancel={handleOncancel}>
                <Form.Item label='商品类别' name="category_id"  rules={[{ required: true, message: '选择类目' }]}>
                    <Select
                        style={{ width: 310 }}
                        onChange={handleSelectCategory}
                        onDropdownVisibleChange={handleSelectDrop}
                        loading={selectLoading}
                        options={categoryOption}
                    />
                </Form.Item>
                <Form.Item label="商品名称" name="productName" rules={[{ required: true, message: '请输入商品名称' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="商品价格" name="price" rules={[{ required: true, message: '请输入商品价格' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="商品库存" name="inventory" rules={[{ required: true, message: '请输入商品库存' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="商品描述" name="description" rules={[{ required: true, message: '请输入商品描述' }]}>
                    <Input />
                </Form.Item>
            </MyModal>
            {/* 头部 */}
            <div className="tip">
                <p className="tip_top">操作提示</p>
                <ul>
                    <li>1.该页展示了商城所有的商品信息,可对商品进行修改操作</li>
                    <li>2.商家添加商品后,需要耍新页面才能看到最新商品</li>
                </ul>
            </div>
            {/* 中间操作部分 */}
            <div className="operation">
                <div className="button">
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                        setModalOpen(true)
                        setModalTitle('添加商品')
                        setActionType('add')
                    }}>添加商品</Button>
                    <Button type="primary" danger icon={<DeleteOutlined />}>批量删除</Button>
                </div>
                <div className="search">
                    <Form>
                        <Form.Item label="商品内容">
                            <Input placeholder="商品名称/编号" />
                        </Form.Item>
                        <Form.Item label="添加时间">
                            {/* <DatePicker placeholder="选择日期" /> */}
                        </Form.Item>
                        <Button icon={<SearchOutlined />} type="primary">查询</Button>
                    </Form>
                </div>
            </div>
            {/* 表格部分 */}
            <div className="table">
                <Spin spinning={tableLoading} tip='正在加载数据...'>
                    <Table bordered dataSource={dataSource}
                        pagination={{ position: ['bottomCenter'], pageSize: 10 }}
                        scroll={{ y: 400 }}
                        columns={columns}></Table>
                </Spin>
            </div>
        </div >
    )

}

export default ProductList